package com.hd.hdxgddcommon.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 下载文件工具类
 * Created by Administrator on 2018/8/4.
 */
public class DownloadUtil {

    public static ResponseEntity<byte[]> download(File file, String filename) throws Exception {
        return new ResponseEntity<>(FileCopyUtils.copyToByteArray(file), createDownloadHeaders(filename), HttpStatus.CREATED);
    }

    public static ResponseEntity<byte[]> download(byte[] bytes, String filename) throws Exception {
        return new ResponseEntity<>(bytes, createDownloadHeaders(filename), HttpStatus.CREATED);
    }

    private static HttpHeaders createDownloadHeaders(String filename) throws UnsupportedEncodingException {
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名 , 解决中文名称乱码问题
        String encode = URLEncoder.encode(filename, "UTF-8");
        //通知浏览器以 attachment(下载方式) 打开 zip
        headers.setContentDispositionFormData("attachment", encode);
        //application/octet-stream : 二进制流数据(最常见的文件下载)
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return headers;
    }
}
